package com.mysher.myplugin;
import com.esotericsoftware.minlog.Log;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.SelectionModel;
import com.intellij.openapi.ui.popup.Balloon;
import com.intellij.openapi.ui.popup.JBPopupFactory;
import com.intellij.ui.JBColor;
import org.apache.http.util.TextUtils;
import org.jetbrains.annotations.NotNull;

import java.awt.*;
import java.util.ArrayList;
import java.util.List;

public class MyAction extends AnAction implements HttpUtils.HttpCallback{

    private Editor mEditor;
    private int fadeoutTime = 0;

    @Override
    public void actionPerformed(AnActionEvent e) {
        mEditor = e.getData(PlatformDataKeys.EDITOR);
        if (null == mEditor) return;
        SelectionModel model = mEditor.getSelectionModel();
        String selectedText = model.getSelectedText();


        if (!TextUtils.isEmpty(doText(selectedText))) {
            HttpUtils.doGetAsync(doText(selectedText), this);
        }
    }

    public static void main(String[] args) {

    }

    /**
     * 处理驼峰式写法、下划线写法、点号写法的方法
     *
     * @param s
     * @return
     */
    private String doText(String s) {
        List<Integer> index = new ArrayList<>(0);
        char[] cs = s.toCharArray();
        StringBuilder sb = new StringBuilder(s);
        int oldIndex = 0;
        for (int i = 0; i < cs.length; i++) {
            if (cs[i] >= 'A' && cs[i] <= 'Z') {
                if (i - oldIndex > 1) {
                    index.add(i);
                }
                oldIndex = i;
            }
        }
        System.out.println("index size:" + index.size());
        for (int i = 0; i < index.size(); i++) {
            sb.insert(index.get(i) + i, " ");
        }
        System.out.println(sb.toString());

        //把所有, . -转换成空格
        return sb.toString().replace("-", " ").replace(".", " ").replace(",", " ").replace("_", " ");
    }

    /**
     * 每个单词第一个字母大写
     *
     * @param str
     * @return
     */
    public static String toUpperFirstCode(String str) {
        String[] strs = str.split(" ");
        StringBuilder sb = new StringBuilder();
        for (String strTmp : strs) {
            char[] ch = strTmp.toCharArray();
            if (ch[0] >= 'a' && ch[0] <= 'z') {
                ch[0] = (char) (ch[0] - 32);
            }
            String strT = new String(ch);
            sb.append(strT).append(" ");
        }
        return sb.toString().trim();
    }

    @Override
    public void onSuccess(TranslateBean bean) {
        String content = null;
        if (bean.getBasic() != null && !bean.getBasic().getExplains().isEmpty() && bean.getBasic().getExplains().size() > 0) {
            content = bean.getTranslation().get(0) + "\n" + bean.getBasic().getExplains().get(0);
        } else {
            content = bean.getTranslation().get(0);
        }

        if (getSubStr(content, " ") > 0) {
            String content_ = content.replaceAll(" ", "_").toUpperCase();
            String contentHump = toUpperFirstCode(content).replaceAll(" ", "");
            content = content + "\n" + content_ + "\n" + contentHump;
        }
        showPopupBalloon(mEditor, content);

    }

    /**
     * 获取字符串出现的个数
     *
     * @param str 传进来的原字符串
     * @param chs 传进来的要查找的字符串
     * @return 统计字符串出现的个数
     */
    public int getSubStr(String str, String chs) {
        // 用空字符串替换所有要查找的字符串
        String destStr = str.replaceAll(chs, "");
        // 查找字符出现的个数 = （原字符串长度 - 替换后的字符串长度）/要查找的字符串长度
        return (str.length() - destStr.length()) / chs.length();
    }

    private void showPopupBalloon(Editor mEditor, String content) {
        if (content.length() <= 5) {
            fadeoutTime = 5 * 1000;
        } else if (content.length() <= 30) {
            fadeoutTime = 20 * 1000;
        } else {
            fadeoutTime = 60 * 1000;
        }
        //
        ApplicationManager.getApplication().invokeLater(() -> {
            JBPopupFactory factory = JBPopupFactory.getInstance();
            factory.createHtmlTextBalloonBuilder(content, null, new JBColor(new Color(186, 238, 186),
                    new Color(73, 117, 73)), null).setFadeoutTime(fadeoutTime)
                    .createBalloon()
                    .show(factory.guessBestPopupLocation(mEditor), Balloon.Position.below);
        });
    }

    @Override
    public void onFail(String errorMsg) {
        showPopupBalloon(mEditor, errorMsg);
    }
}
